import type { Router } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { startProgress, stopProgress } from '@vben/utils';

import { useTitle } from '@vueuse/core';

import { $t } from '#/locales';
import { coreRouteNames, dynamicRoutes } from '#/router/routes';
import { useAuthStore } from '#/store';

import { generateAccess } from './access';

/**
 * 通用守卫配置
 * @param router
 */
function setupCommonGuard(router: Router) {
  // 记录已经加载的页面
  const loadedPaths = new Set<string>();

  router.beforeEach(async (to) => {
    to.meta.loaded = loadedPaths.has(to.path);

    // 页面加载进度条
    if (!to.meta.loaded && preferences.transition.progress) {
      startProgress();
    }
    return true;
  });

  router.afterEach((to) => {
    // 记录页面是否加载,如果已经加载，后续的页面切换动画等效果不在重复执行

    if (preferences.tabbar.enable) {
      loadedPaths.add(to.path);
    }

    // 关闭页面加载进度条
    if (preferences.transition.progress) {
      stopProgress();
    }

    // 动态修改标题
    if (preferences.app.dynamicTitle) {
      const { title } = to.meta;
      // useTitle(`${$t(title)} - ${preferences.app.name}`);
      useTitle(`${$t(title)} - ${preferences.app.name}`);
    }
  });
}

/**
 * 匹配路径
 * permission.path = "/xx/edit" 但route.path = "/xx/edit/:id?" 这种情况，其中id可以为任意值，如meetingId roleId等，
 */
function matchPaths(routePath, permissionPath) {
  const routeParts = routePath.path.split('/');
  const permissionParts = permissionPath.path.split('/');

  if (routePath.name === permissionPath.id) {
    return true;
  }

  if (permissionParts.length > routeParts.length) {
    return false;
  }

  return routeParts.every((part, index) => {
    return part === permissionParts[index] || part.startsWith(':');
  });
}

// 过滤路由，只保留第三个数据源配置的路由
function filterRoutesByPermissions(routes, permissions, staticRouteKeys) {
  const filteredRoutes = [];
  for (const route of routes) {
    // console.log('[ route ] >', route)
    // console.log('[ permission.path ] >', permissions)

    const permission = permissions.find((permission) =>
      matchPaths(route, permission),
    );

    const isStaticRoute = staticRouteKeys.includes(route.name);

    if (permission || isStaticRoute) {
      const newRoute = { ...route };
      if (permission) {
        newRoute.meta = {
          ...newRoute.meta,
          title: permission.name,
        };
        if (permission.order) {
          newRoute.meta.order = permission.order;
        }
      }
      if (route.children) {
        newRoute.children = filterRoutesByPermissions(
          route.children,
          permissions,
          staticRouteKeys,
        );
      }
      filteredRoutes.push(newRoute);
      // console.log(JSON.parse(JSON.stringify(filteredRoutes)));
    }
  }

  return filteredRoutes;
}

/**
 * 权限访问守卫配置
 * @param router
 */
function setupAccessGuard(router: Router) {
  router.beforeEach(async (to, from) => {
    const accessStore = useAccessStore();
    const userStore = useUserStore();
    const authStore = useAuthStore();

    // 基本路由，这些路由不需要进入权限拦截
    if (coreRouteNames.includes(to.name as string)) {
      if (to.path === LOGIN_PATH && accessStore.accessToken) {
        return decodeURIComponent(
          (to.query?.redirect as string) ||
            userStore.userInfo?.homePath ||
            DEFAULT_HOME_PATH,
        );
      }
      return true;
    }

    // accessToken 检查
    if (!accessStore.accessToken) {
      // 明确声明忽略权限访问权限，则可以访问
      if (to.meta.ignoreAccess) {
        return true;
      }

      // 没有访问权限，跳转登录页面
      if (to.fullPath !== LOGIN_PATH) {
        return {
          path: LOGIN_PATH,
          // 如不需要，直接删除 query
          query:
            to.fullPath === DEFAULT_HOME_PATH
              ? {}
              : { redirect: encodeURIComponent(to.fullPath) },
          // 携带当前跳转的页面，登录后重新跳转该页面
          replace: true,
        };
      }
      return to;
    }

    // 是否已经生成过动态路由
    if (accessStore.isAccessChecked) {
      return true;
    }

    // 生成路由表
    // 当前登录用户拥有的角色标识列表
    const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());
    const userRoles = userInfo.roles ?? [];

    // debugger

    // 二开，从统一授权获取菜单key值，遍历本地所有菜单进行添加

    // const staticRouteKeys = [
    //   'Dashboard',
    //   'home',
    //   'User',
    //   'UserCenter',
    //   'UserTodo',
    //   'IFrame',
    //   'MeetingStandingBook',
    //   'MeetingStart',
    //   'DutyStandingBook',
    //   'ContractInfo',
    // ];

    // const r = await Apis.system.menu.getList();
    // let originRouters = r.rows[0].children;
    // // 提取数据的函数
    // const extractData = (input: any[]) => {
    //   const result: any[] = [];
    //   function traverse(node: any) {
    //     if (node.id && node.name) {
    //       result.push({
    //         id: node.id,
    //         path: node.remark,
    //         name: node.name,
    //         order: node.showOrder || 0,
    //       });
    //     }
    //     if (node.children && node.children.length > 0) {
    //       for (const child of node.children) {
    //         traverse(child);
    //       }
    //     }
    //   }

    //   for (const node of input) {
    //     traverse(node);
    //   }

    //   return result;
    // };
    // // console.log('originRouters', originRouters)
    // originRouters = extractData(originRouters);
    // // console.log('originRouters', originRouters)

    // let finalRoutes = filterRoutesByPermissions(
    //   dynamicRoutes,
    //   originRouters,
    //   staticRouteKeys,
    // );
    // console.log(originRouters);
    // // console.log('finalRoutes', finalRoutes)

    // // console.log('dynamicRoutes', dynamicRoutes)
    // // console.log('userInfo', userInfo)

    // if (userInfo.accountId == 'Admin.itl' || userInfo._isSkip) {
    //   finalRoutes = dynamicRoutes;
    // }

    const finalRoutes = dynamicRoutes;
    // console.log(userInfo)

    // 生成菜单和路由
    const { accessibleMenus, accessibleRoutes } = await generateAccess({
      roles: userRoles,
      router,
      // 则会在菜单中显示，但是访问会被重定向到403
      routes: finalRoutes,
    });

    console.log(accessibleMenus);
    console.log(accessibleRoutes);

    // 保存菜单信息和路由信息
    accessStore.setAccessMenus(accessibleMenus);
    accessStore.setAccessRoutes(accessibleRoutes);
    accessStore.setIsAccessChecked(true);
    const redirectPath = (from.query.redirect ?? to.fullPath) as string;

    return {
      ...router.resolve(decodeURIComponent(redirectPath)),
      replace: true,
    };
  });
}

/**
 * 项目守卫配置
 * @param router
 */
function createRouterGuard(router: Router) {
  /** 通用 */
  setupCommonGuard(router);
  /** 权限访问 */
  setupAccessGuard(router);
}

export { createRouterGuard };
